package com.ra.service.impl;

import com.ra.service.JwtTokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static com.ra.constant.AuthConstant.*;
/**
 * Author : 今晚几点睡_Ada
 * Date: 2023/3/9
 * Time: 10:01
 * 注:
 */
@Service
public class JwtTokenServiceImpl implements JwtTokenService {




    /**
     * 根据负载生成JWT Token
     *
     * @param claims
     * @return
     */
    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,SECRET)
                .compact();
    }
    /**
     * 从token中获取JWT中的负载
     *
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
          //  claims = e.getClaims();
        }
        return claims;
    }
    /**
     * 生成token过期时间
     *
     * @return
     */
    public Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + EXPIRE_TIME * 1000);
    }
    /**
     * 从token中获取过期时间
     *
     * @param token
     * @return
     */
    public Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }
    /**
     * 判断token是否失效
     *
     * @param token
     * @return
     */
    public boolean isTokenExpired(String token) {


        Date expiredDate = getExpiredDateFromToken(token);

      //  return expiredDate.before(new Date());
        return new Date(System.currentTimeMillis()).after(expiredDate);
    }
    /**
     * 从token中获取登录用户名
     *
     * @param token
     * @return
     */
    public String getUserNameFormToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }
    /**
     * 验证token是否有效
     *
     * @param token
     * @param userDetails
     * @return
     */

    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFormToken(token);
        return username.equals(userDetails.getUsername()) &&
                !isTokenExpired(token);
    }
    /**
     * 根据用户信息生成token
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }
    /**
     * 判断token是否可以被刷新
     * @param token
     * @return
     */
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }
    /**
     * 刷新token
     * @param token
     * @return
     */
    public String refreshToken(String token){
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }

    @Override
    public void delLoginUser(Integer userId) {

    }


}
